from flask import g
from flask import request
from flask import session,render_template,current_app, jsonify

from info import db
from info.models import User, Category, News
from info.utils.response_code import RET
from . import news_blue
from info.utils.commons import login_required


#项目首页
@news_blue.route("/")
@login_required
def index():

    """
    项目首页，右上角的用户信息展示(检查用户登录)
    从redis中获取user_id,根据user_id查询mysql，获取用户信息
    :return:
    """
    user = g.user
    # #从redis数据库中获取user_id
    # user_id = session.get("user_id")
    # user = None
    # if user_id:
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger.error(e)

    #新闻分类数据
    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(error=RET.DBERR,errmsg="查询数据失败")
    if not categories:
        return jsonify(error=RET.NODATA,errmsg="无新闻分类")
    category_list = []
    for category in categories:
       category_list.append(category.to_dict())

    #新闻点击排行
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(6)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(error=RET.DBERR,errmsg="查询新闻排行数据失败")
    if not news_list:
        return jsonify(error=RET.NODATA, errmsg="无新闻分类排行数据")
    news_click_list =[]
    for news in news_list:
        news_click_list.append(news.to_dict())


    #定义字典数据，返回模板
    data = {
        "user_info":user.to_dict() if user else None,
        "category_list":category_list,
        "news_click_list":news_click_list
    }
    # session["user"] = "2018"
    return render_template("news/index.html",data=data)

#新闻列表数据加载
@news_blue.route('/news_list')
def get_news_list():
    cid = request.args.get("cid","1")
    page = request.args.get("page","1")
    per_page = request.args.get("per_page","10")
    print(cid,page)
    #检查数据类型
    try:
        cid,page,per_page = int(cid),int(page),int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(error=RET.PARAMERR,errmsg="参数类型错误")
    #根据新闻分类查询数据
    filters =[]
    #判断新闻分类id不是最新
    if cid > 1:
        filters.append(News.category_id == cid)
    #根据新闻分类查询数据
    try:
        #*filters相当于python中的拆包，返回的是sqlachemy对象相当于News.category_id == cid
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page,per_page,False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(error=RET.DBERR,errmsg="查询新闻列表数据失败")
    #使用分页对象获取分页后的新闻数据
    news_list = paginate.items #新闻列表
    total_page =paginate.pages#总页数
    current_page = paginate.page#当前页数
    new_dict_list =[]
    for news in news_list:
        new_dict_list.append(news.to_dict())
    #返回数据
    data ={
        'new_dict_list':new_dict_list,
        "total_page":total_page,
        "current_page":current_page
    }
    return jsonify(error=RET.OK,errmsg ="OK",data=data)

#新闻详情数据
@news_blue.route("/<int:news_id>")
@login_required
def get_news_detail(news_id):

    user = g.user
    # # 从redis数据库中获取user_id
    # user_id = session.get("user_id")
    # user = None
    # if user_id:
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger.error(e)

    # 新闻点击排行
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(6)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(error=RET.DBERR, errmsg="查询新闻排行数据失败")
    if not news_list:
        return jsonify(error=RET.NODATA, errmsg="无新闻分类排行数据")
    news_click_list = []
    for news in news_list:
        news_click_list.append(news.to_dict())
    #新闻详情数据展示
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(error=RET.DBERR, errmsg="查询新闻详情数据失败")
    if not news:
        return jsonify(error=RET.NODATA, errmsg="无新闻详情数据")
    is_collected = False
    if user and news  in user.collection_news:
        is_collected =True

    # 定义字典数据，返回模板
    data = {
        "user_info": user.to_dict() if user else None,
        "news_click_list": news_click_list,
        "news_detail":news.to_dict(),
        "is_collected":is_collected
    }


    return render_template("news/detail.html",data=data)

#新闻收藏
@news_blue.route("/news_collect",methods=["POST"])
@login_required
def news_collect():
    user = g.user
    if not user:
        return jsonify(error=RET.SESSIONERR,errmsg="用户为登录")
    news_id = request.json.get("news_id")
    action = request.json.get("action")
    if not all([news_id,action]):
        return jsonify(error=RET.PARAMERR,errmsg="参数不完整")
    try:
        news_id=int(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(error=RET.PARAMERR, errmsg="参数类型错误")
    if action not in ['collect','cancel_collect']:
        return jsonify(error=RET.PARAMERR,errmsg="参数格式错误")
    #根据news_id查询mysql数据库确认新闻的存在
    try:
        news=News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(error=RET.DBERR, errmsg="查询新闻数据失败")
    #判断查询结果
    if not news:
        return jsonify(error=RET.NODATA,errmsg="查询新闻数据失败")
    #如果用户选择收藏
    if action == "collect":
        if news not in user.collection_news:
            user.collection_news.append(news)
        else:
            user.collection_news.remove(news)
        return jsonify(error=RET.OK,errmsg="OK")
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(error=RET.DBERR,errmsg="保存数据是失败")
    return jsonify(error=RET.OK,errmsg="OK")



@news_blue.route("/favicon.ico")
def favicon():
    return current_app.send_static_file("news/favicon.ico")




